import java
#import java.lang.String as string
from com.sleepycat.je import *
import java.io.File as File;
import cPickle
import javax,zlib,re,org
import string


class Dict:
	header = None
	def __init__(self,homef,dbName):
		self.envConfig = EnvironmentConfig();
		self.envConfig.setAllowCreate(True);
		home = java.io.File(homef)
		self.env = Environment(home, self.envConfig);
		self.dbConfig = DatabaseConfig();
		self.dbConfig.setAllowCreate(True);
		
		self.geneDB = self.env.openDatabase(None, dbName, self.dbConfig);
		# check if db already exists
		
		try:
			self.header=self['header']
		except:
			pass

	
	def peek(self,filename):
		pass
		# read the first line of the file and get a potential header string.
		
	def __del__(self):
		self.geneDB.close()
		self.env.close()
		del(self)

	def __getitem__(self,key):
		try:
			rex=None
			if isinstance(key,org.python.core.PyTuple):
				rex = key[1]
				key = key[0]
			
			dbkey=java.lang.String(key)
			theKey = DatabaseEntry(dbkey.getBytes("UTF-8"));
			value = DatabaseEntry('')
			self.geneDB.get(None,theKey,value,LockMode.DEFAULT)
			s = zlib.decompress(value.data)
			X = cPickle.loads(s)
			
			if rex is not None:
				r=re.compile(rex)
				for x in X.keys():
					if r.match(x):
						return X[x]
						pass
					pass
				pass
			else:
				return X
		except:
			return None

	def __setitem__(self,key,value):
		key=java.lang.String(key)
		theKey = DatabaseEntry(key.getBytes("UTF-8"));
		value = zlib.compress(cPickle.dumps(value))
		#value = cPickle.dumps(value)
		
		theData = DatabaseEntry(value);
		self.geneDB.put(None, theKey, theData);

	def makeDBFromAFFY(self,filename,parent=None):
		try:
			instream = java.io.FileInputStream(java.io.File(filename))
		except:
			print "File Does not Exist"
			return
			
		if parent is not None:
			plines = javax.swing.ProgressMonitorInputStream(parent,'Loading File' + filename, instream)
		else:
			plines=instream
		
		lines=java.io.BufferedReader(java.io.InputStreamReader(plines))
		line = lines.readLine()

		Q = string.split(line)
		while line != None:
			line = lines.readLine()
			if line is None:
				break
			else:
				try:
					Q = string.split(line)
					i=0
					Q[1]=string.replace(Q[1],',','')
					self[Q[0]] = Q[1]
					print Q[0]
				except:
					pass #skipping header


